import { getURLParams, sleep } from "@/comm/tooler";
import { toast } from "@/components/toast/toast";
import { Bus, CHART_CHAIN_SUBSCRIBE, CHART_KLINE_SUBSCRIBE, CONN_ACTIVITY, KLINE_CLEAR, KLINE_RESET, START_CONN, CHANGE_HOME_CHART } from "@/connetion/Bus";
import { useAccount } from "@/stores/account";
import { useAction } from "@/stores/action";
import { useActivity } from "@/stores/activity";
import { CoinType, IInterval, useKline } from "@/stores/kline";
import { useLayout } from "@/stores/layout";
import { useSignal } from "@/stores/signal";
import { useUser } from "@/stores/user";
import { onMounted } from "vue";
import { useRouter } from "vue-router";

export const useCore = function () {
	const kline = useKline();
	const user = useUser();
	const account = useAccount();
	const activity = useActivity();
	const signal = useSignal();
	const action = useAction();
	const router = useRouter();
    const layout = useLayout()

	const init = async () => {
		await kline.init();
		console.log("幣對初始化完成");

		activity.loadAllActivity();

		let isLogin = await user.checkLogin();
		if (isLogin) {
			await user.getUserInfo();
			//第三方登录未绑定邮箱, 弹出绑定邮箱页面
			// if (user.noEmail) {
			// 	account.changePopRegister(true);
			// }
		}

        if(layout.isMobile && !!user.info){
            if(location.href.includes("/reward") == false){
                location.href = "/reward";
            }
            
        }

        if(!!user.info){
            return
        }

		const param = getURLParams();
		//从推荐链接进入, 弹出注册页面
		if (param && param.recommend) {
			user.changeRecommend(param.recommend);
			if (user.noEmail) {
				account.changeIsBindEmail(true);
			}
			else {
				account.changeIsBindEmail(false);
			}
			account.changePopRegister(true);

		}
	};

	const switchCoin = async (val: CoinType) => {
		Bus.emit(CHANGE_HOME_CHART)
		kline.changeCurCoin(val);
        localStorage.setItem("K_TYPE", val.symbol);
		await upateHistory();
		Bus.emit(CHART_KLINE_SUBSCRIBE, kline.param);
		Bus.emit(CHART_CHAIN_SUBSCRIBE, val.tokenAddress);
	};

	const switchCoinByName = async (name: string) => {
		const coin = kline.map.find(i => i.symbol === name);
		if (coin) {
			switchCoin(coin);
		}
		else {
			console.log("找不到对应coin");
			toast("The corresponding currency cannot be found");
		}
	};

	const switchCoinByHash = async (hash: string) => {
		const coin = kline.map.find(i => i.tokenAddress === hash);
		if (coin) {
			switchCoin(coin);
		}
		else {
			console.log("找不到对应coin");
			toast("The corresponding currency cannot be found");
		}
	};

	const switchInterval = async (val: IInterval) => {
		kline.changeCurInterval(val);
        localStorage.setItem("K_TIME", val.name);
		await upateHistory();
	};

	const upateHistory = async () => {
		// console.log("jsz", "更新历史数据");
		while (!kline.curCoin) {
			// console.log("jsz", "wait");
			await sleep(200);
		}
		// kline.historyList = []
		kline.list = []
		Bus.emit(KLINE_CLEAR);
		await kline.loadHistory();
		// console.log(kline.list.map(x=>console.log(new Date(x.timestamp))),"tetetetetettete")

		// await kline.calcJunLine(kline.list)
		// if (kline.curInterval.name !== "S1") {
		// 	await kline.loadMore(kline.list[0].timestamp, 1000)
		// }
		// activity.loadHistory(kline.curCoin.tokenAddress);
		// signal.loadHistory(kline.curCoin.symbol, kline.curInterval.name);
        if(kline.list?.length > 2){
            action.loadData(kline.curCoin.tokenAddress, kline.list[0].timestamp, kline.list[kline.list.length - 1].timestamp);
        }
		
		Bus.emit(KLINE_RESET);
		// console.log("jsz", "更新历史数据结束");
	};

	const changeThemeColor = () => {
		const root = document.documentElement;
		// 修改--main属性的值
		root.style.setProperty("--main", "#ff9900");
	};

	const goHome = () => {
		let obj = ["/entity", "/coin", "/token", "/address"].find(i => location.href.includes(i));
		if (obj) {
			location.replace("/");
			return;
		}
		router.push("/");
	};

	return {
		switchCoin,
		switchCoinByName,
		switchCoinByHash,
		switchInterval,
		upateHistory,
		goHome,
		init
	};
};
